package com.example.androidmqtt.Service.ServiceImpl.ServiceImpl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.androidmqtt.Entry.*;
import com.example.androidmqtt.Mapper.*;
import com.example.androidmqtt.Service.ServiceImpl.PlateService;
import com.example.androidmqtt.Vo.NewsDetail;
import com.example.androidmqtt.Vo.SubPlate;
import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.BreakIterator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: pjg
 * @time: 2022/9/14
 */
@Service
public class PlateServiceImpl extends ServiceImpl<NewsMapper, News> implements PlateService {

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private SubscribeMapper subscribeMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private UserMapper userMapper;

    //全局列表
    private List<NewsDetail> newsAll = new ArrayList<>();
    //用户，用户订阅列表
    private Map<Integer, List<NewsDetail>> newsSub = new HashMap<>();


    @Override
    public List<NewsDetail> GetAllNews() {
        if (newsAll.isEmpty())
            getNews(null);
        return newsAll;
    }

    @Override
    public List<NewsDetail> GetNewsByUser(Integer userId) {
        if (!newsSub.containsKey(userId) || newsSub.get(userId).isEmpty())
            getNews(userId);
        return newsSub.get(userId);
    }

    //更新news值
    public void getNews(Integer userId) {
        List<NewsDetail> news = null;
        try {
            //自定义SQL查询语句
            if (userId != null)
                news = newsMapper.selectListByUser(userId);
            else
                news = newsMapper.selectAll();

            //时间格式化
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date nowTime = format.parse(format.format(new Date()));
            news.forEach(per -> {
                try {
                    Date pubTime = format.parse(per.getNewsPublishTime());
                    //计算与当前时间的时间差（分钟）
                    int between = (int) DateUtil.between(pubTime, nowTime, DateUnit.MINUTE);
                    String diff = between / 1440 >= 1 ? "" + between / 1440 + "天前" :
                            between / 60 >= 1 ? "" + between / 60 + "小时前" :
                                    between >= 1 ? "" + between + "分钟前" : "刚刚";
                    per.setNewsPublishTime(diff);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userId == null)
            newsAll = news;
        else
            newsSub.put(userId, news);
    }

    @Override
    public List<NewsDetail> GetNewsBySearch(String key, Integer userId) {
        List<NewsDetail> result = new ArrayList<>();
        if (userId == null)
            newsAll.forEach(per -> {
                if (per.getNewsAuthor().contains(key) || per.getNewsTitle().contains(key) || per.getNewsContent().contains(key))
                    result.add(per);
            });
        else {
            newsSub.get(userId).forEach(per -> {
                if (per.getNewsAuthor().contains(key) || per.getNewsTitle().contains(key) || per.getNewsContent().contains(key))
                    result.add(per);
            });
        }
        return result;
    }

    @Override
    public NewsDetail GetNewsDetail(Integer newsID) {
        //从缓存中获取，有对应数据，除参数意外
        for (NewsDetail detail : newsAll) {
            if (detail.getNewsId().equals(newsID))
                return detail;
        }
        return null;
    }

    @Override
    public int PubContent(int userId, String title, String content, String appendix) {
        int department = userMapper.getDepartment(userId);
        if (appendix == null)
            appendix = "";
        News one = new News(title, content, userId, department, appendix);

        int insert = newsMapper.insert(one);

        if (insert>0) {
            //更新newsAll
            getNews(null);
            getNews(userId);

            //更新用户未读表
            updateMessage(one.getNewsAuthor(),one.getNewsDepartment(),one.getNewsId());
            return one.getNewsId();
        }
        return 0;

    }

    private void updateMessage(Integer newsAuthor,Integer newsDepartment,Integer newsId) {
        try {
            //在该部门中，将本人剔除
            List<Subscribe> subscribes = subscribeMapper.selectList(new QueryWrapper<Subscribe>().eq("sub_department", newsDepartment).ne("sub_user",newsAuthor));
            ArrayList<Integer> userIds = new ArrayList<>();
            for (Subscribe subscribe : subscribes) {
                userIds.add(subscribe.getSubUser());
            }
            for (Integer userId : userIds) {
                messageMapper.insert(new Message(userId, newsId));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public int Subscribe(Integer userId, Integer department) {
        int flag;
        QueryWrapper<Subscribe> wrapper = new QueryWrapper<>();
        wrapper.eq("sub_user", userId).eq("sub_department", department);
        Subscribe isExist = subscribeMapper.selectOne(wrapper);
        //取消订阅后重新订阅修改字段即可
        if (isExist != null && isExist.getIsCancel() == 1) {
            flag = subscribeMapper.updateByCancel(isExist, 0);

        }
        else if (isExist != null){
            return -1;
        }
        else {
            //新订阅
            Subscribe one = new Subscribe(userId, department);
            flag = subscribeMapper.insert(one);
        }
        //更新newsSub
        getNews(userId);
        return flag;
    }

    @Override
    public int unSubscribe(Integer userId, Integer department) {
        QueryWrapper<Subscribe> wrapper = new QueryWrapper<>();
        wrapper.eq("sub_user", userId).eq("sub_department", department);
        Subscribe one = subscribeMapper.selectOne(wrapper);
        int flag = subscribeMapper.updateByCancel(one, 1);
        //更新newsSub
        getNews(userId);
        return flag;
    }

    @Override
    public List<SubPlate> getUserPlate(Integer userId) {
        List<SubPlate> result = new ArrayList<>();
        List<Department> departments = departmentMapper.selectList(new QueryWrapper<Department>().orderByAsc("department_id"));
        List<Subscribe> sub_user = subscribeMapper.selectList(new QueryWrapper<Subscribe>().eq("iscancel",0).eq("sub_user", userId).orderByAsc("sub_department"));
        User user = userMapper.selectById(userId);
        //将用户所属部门放在第一位
        Department belong = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_id", user.getUserDepartment()));
        result.add(new SubPlate(belong.getDepartmentName(),belong.getDepartmentId(),belong.getTag(), 1,belong.getDepartmentAvatar()));
        departments.remove(belong.getDepartmentId() - 1);

        departments.forEach(per -> {
            sub_user.forEach(item -> {
                if (item.getSubDepartment().equals(per.getDepartmentId())) {
                    result.add(new SubPlate(per.getDepartmentName(),per.getDepartmentId(),per.getTag(), 1,per.getDepartmentAvatar()));
                    per.setDepartmentName("flag");
                }
            });
        });
        //遍历未订阅的板块
        departments.forEach(per -> {
            if (!per.getDepartmentName().equals("flag"))
            result.add(new SubPlate(per.getDepartmentName(),per.getDepartmentId(),per.getTag(), 0,per.getDepartmentAvatar()));
        });
        return result;
    }
}
